using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
using System.IO;
using Elmah;
using SubSonic;
using SurveyHost.Core.DAL;
using SurveyHost.Core.Controls;

namespace SurveyHost.Core
{
    /// <summary>
    /// Thrown when a type of answer is not found.  
    /// This is often caused when an answer type has been created, then used in a question, and then removed from the installation directory.
    /// </summary>
    public class AnswerTypeNotFoundException : System.Exception
    {
        private string _typeName;

        /// <summary>
        /// The assembly qualified name of the type not found
        /// </summary>
        public string TypeName
        {
            get { return _typeName; }
            set { _typeName = value; }
        }

        public AnswerTypeNotFoundException(string typename)
        {
            TypeName = typename;
        }
        public AnswerTypeNotFoundException() { }
    }

    /// <summary>
    /// AddinHelper is a static class that is used to load and verify system addins.  Currently, addins are restricted to answer types.
    /// </summary>
    public static class AddinHelper
    {
        /// <summary>
        /// Loads DLLs in a given <paramref name="path"/> that implement a given <paramref name="pluginInterface"/>
        /// </summary>
        /// <param name="path">The path.</param>
        /// <param name="pluginInterface">The plugin interface.</param>
        /// <param name="recurse">if set to <c>true</c> checks all subdirectories of <paramref name="path"/></param>
        private static void LoadPluginsInPath(string path, Type pluginInterface, bool recurse)
        {
            DirectoryInfo di = new DirectoryInfo(path);
            if (recurse)
                foreach (DirectoryInfo cd in di.GetDirectories())
                    LoadPluginsInPath(cd.Name, pluginInterface, recurse);
            

            foreach (FileInfo file in di.GetFiles())
            {
                if (!Path.GetExtension(file.Name).Equals(".dll", StringComparison.OrdinalIgnoreCase))
                    continue;
                //Assembly.LoadFrom(file.FullName);
            }
        }

        /// <summary>
        /// retrieves all types that implement an interface or extend a base type within the current appdomain
        /// </summary>
        /// <param name="baseType"></param>
        /// <returns></returns>
        public static List<Type> GetAllImplementingTypes(Type interfaceType)
        {
            if (interfaceType == null) throw new ArgumentNullException("interfaceType");

            List<Type> result = new List<Type>();

            LoadPluginsInPath(WebUtil.BinPath,interfaceType,true);

            AppDomain app = AppDomain.CurrentDomain;
            Assembly[] ass = app.GetAssemblies();
            Type[] types;
            string fullname;
            foreach (Assembly a in ass)
            {
                fullname = a.FullName;
                if (string.IsNullOrEmpty(fullname)) continue;

                if (fullname.EndsWith("b77a5c561934e089") || // ms
                    fullname.EndsWith("b03f5f7f11d50a3a") || // ms
                    fullname.EndsWith("f8bb63aa9d6969e8") || // excelpackage
                    fullname.EndsWith("eadb47849839a332"))   // Subsonic
                    continue;
                types = a.GetTypes();
                foreach (Type t in types)
                {
                    if (t.IsInterface) continue;
                    if (t.IsAbstract) continue;
                    foreach (Type iface in t.GetInterfaces())
                    {
                        if (!iface.Equals(interfaceType)) continue;
                        result.Add(t);
                        break;
                    }
                }
            }
            return result;
        }

        /// <summary>
        /// Refreshes the AnswerObjectType table in the database, verifying that types used in questions exist, and adding
        /// newly discovered types in the Bin folder.
        /// </summary>
        /// <exception cref="AnswerTypeNotFoundException">Thrown if an answer type is found in the database but cannot be located.</exception>
        public static void RefreshAnswerObjectTypes()
        {
            // addins are dumped in the app_data directory
            List<Type> questionTypes = AddinHelper.GetAllImplementingTypes(typeof(ISurveyQuestion));

            AnswerObjectTypeCollection aotc = new AnswerObjectTypeCollection();
            aotc.Load();
            Type t;
            // toarray so we can modify aotc while enumerating it
            foreach (AnswerObjectType aot in aotc.ToArray())
            {
                // get type as described in db; remove from collection if not found in assy
                t = Type.GetType(aot.AssemblyQualifiedName, false, true);
                if (t == null) // cannot load the type; we're screwed now!
                {
                    throw new AnswerTypeNotFoundException(aot.AssemblyQualifiedName);
                }
                // remove types already in the db; they don't need to be added
                questionTypes.Remove(t);
            }
            AnswerObjectType at;
            foreach (Type type in questionTypes)
            {
                at = new AnswerObjectType();
                at.AnswerTypeName = type.Name;
                at.AssemblyQualifiedName = type.AssemblyQualifiedName;
                at.AnswerConfigurationHelpText = GetHelpText(type).Substring(0,500);
                at.Save();
            }
        }


        /// <summary>
        /// Gets the help text for an answer object type
        /// </summary>
        /// <param name="type">The type.</param>
        /// <returns></returns>
        private static string GetHelpText(Type type)
        {
            if (type == null
                || !typeof(BaseSurveyQuestion).IsAssignableFrom(type))
                return "No help text available.";
            using (BaseSurveyQuestion bsq = (BaseSurveyQuestion)Activator.CreateInstance(type))
            {
                return bsq.ConfigurationHelpText;
            }
        }
    }
}
